import React, {Component} from 'react'
import {Table, Column, Cell} from 'fixed-data-table-2'
import Dimensions from 'react-dimensions'
import { Spin } from 'antd';
import  store from '../../../stores/main';

import styles from  './index.scss'

class TextCell extends Component {
    render() {
        const {data, rowIndex, columnKey, ...props} = this.props;
        return (
            <Cell {...props}>
                {data[rowIndex][columnKey]}
            </Cell>
        );
    }
}
//排序选项
const SortTypes = {
    ASC: 'ASC',
    DESC: 'DESC',
};
//排序组件
class SortHeaderCell extends Component {
    constructor(props) {
        super(props);

        this._onSortChange = this._onSortChange.bind(this);
    }
    _onSortChange(e) {
        e.preventDefault();

        if (this.props.onSortChange) {
            this.props.onSortChange(
                this.props.columnKey,
                this.props.sortDir === SortTypes.DESC ? SortTypes.ASC : SortTypes.DESC
            );
        }
    }
    render() {
        var {onSortChange, sortDir, children, ...props} = this.props;
        return (
            <Cell {...props}>
                <a onClick={this._onSortChange}>
                    {children} {sortDir ? (sortDir === SortTypes.DESC ? '↑' : '↓') : ''}
                </a>
            </Cell>
        );
    }
}


class FlexGrow extends Component {
    constructor(props) {
        super(props);
        let columnWidths = {};
        let columnOrder = [];
        //初始化每一列的宽度，默认宽度100
        this.props.tableColumnData.map((e, index) => {
            let columnWidth = 100;
            if(e.columnWidth){
                columnWidth = e.columnWidth;
            }
            columnWidths[e.columnName] = columnWidth;
            columnOrder.push(e.columnName);
        });

        this._dataList = [];
        this._defaultSortIndexes = [];

        this.state = {
            loading: true,
            isHideLeft:false,
            columnWidths: columnWidths,                 //初始化每一列的宽度
            columnOrder: columnOrder,                   //初始化列显示顺序

            sortedDataList: [],           //排序后的数据
            colSortDirs: {},              //列 + 排序的顺序
        };

        this.unsubscribe = store.listen( (data)=>{
            this.setState(data);
        });

        this._onColumnResizeEndCallback = this._onColumnResizeEndCallback.bind(this);
        this._onColumnReorderEndCallback = this._onColumnReorderEndCallback.bind(this);
        this._onSortChange = this._onSortChange.bind(this);
    }

    componentWillUnmount() {
        this.unsubscribe();
    }

    rowHandles = (strHandles, rowObj) => {
        this.props.rowHandles(strHandles, rowObj);
    }

    //拖拽列宽度事件
    _onColumnResizeEndCallback(newColumnWidth, columnKey) {
        this.setState(({columnWidths}) => ({
            columnWidths: {
                ...columnWidths,
                [columnKey]: newColumnWidth,
            }
        }));
    }
    //移动列事件
    _onColumnReorderEndCallback(event) {
        //console.log(event);
        let columnOrder = this.state.columnOrder.filter((columnKey) => {
            return columnKey !== event.reorderColumn;
        });

        if (event.columnAfter) {
            let index = columnOrder.indexOf(event.columnAfter);
            columnOrder.splice(index, 0, event.reorderColumn);
        } else {
            columnOrder.push(event.reorderColumn);
        }
        this.setState({
            columnOrder: columnOrder
        });
    }
    //列排序事件
    _onSortChange(columnKey, sortDir) {
        let sortIndexes = this._defaultSortIndexes.slice();
        sortIndexes.sort((indexA, indexB) => {
            let valueA = this._dataList[indexA][columnKey];
            let valueB = this._dataList[indexB][columnKey];
            if(valueA==null){
                valueA = '-1';
            }
            if(valueB==null){
                valueB = '-1';
            }
            let sortVal = 0;
            if (valueA > valueB) {
                sortVal = 1;
            }
            if (valueA < valueB) {
                sortVal = -1;
            }

            if (sortVal !== 0 && sortDir === SortTypes.ASC) {
                sortVal = sortVal * -1;
            }
            return sortVal;
        });

        let _sortedDataList = [];
        for(let i=0; i<sortIndexes.length; i++){
            _sortedDataList.push(this._dataList[sortIndexes[i]])
        }

        this.setState({
            sortedDataList: _sortedDataList,
            colSortDirs: {
                [columnKey]: sortDir,
            },
        });
    }
    componentWillReceiveProps(nextProps) {
        this._dataList = nextProps.indexList;
        if(this._dataList == null){
            this._dataList = [];
        }
        const size = this._dataList.length;
        this._defaultSortIndexes = [];
        for (let index = 0; index < size; index++) {
            this._defaultSortIndexes.push(index);
        }

        this.setState({
            loading: nextProps.loading,

            sortedDataList: this._dataList,
            colSortDirs: {},
        });
    }

    render() {
        const {containerHeight, containerWidth, ...props} = this.props;
        let containerWidth_hide_left = containerWidth;

        //当左侧隐藏时，列表宽度加上左侧的宽度，
        // 当前this.props.isHideLeft 是从父组件ListBox传过来
        //this.props.isHideLeft 最顶级赋值是在页面 containers/Main/main.js
        if(this.state.isHideLeft){
            containerWidth_hide_left += 240;
        }

        let _tableColumnData = this.props.tableColumnData;
        let tableColumnData = [];
        this.state.columnOrder.map( (columnKey) => { //根据拖拽后的列顺序（this.state.columnOrder）重新对传递过来的列顺序（this.props.tableColumnData）排序
            _tableColumnData.map( (e) => {
                if(e.columnName === columnKey){
                    tableColumnData.push(e);
                }
            });
        });

        let {sortedDataList, colSortDirs} = this.state;
        let rowOperation = this.props.rowOperation;
        let columnWidths = this.state.columnWidths;
        let spinLoading;
        //loading效果
        if(this.state.loading){
            sortedDataList = [];
            spinLoading = <div style={{position: 'absolute', left: '0', right: '0', top: '201px', bottom: '3px',borderRadius: '3px', paddingTop: '37px', marginLeft: '15px', width: containerWidth_hide_left, backgroundColor: 'rgba(0,0,0,0.1)', zIndex: '2'}}>
                                <Spin delay={500} tip="Loading..." style={{position: 'absolute', left: containerWidth_hide_left / 2, bottom: containerHeight / 2,zIndex: '2'}} size="large" />
                         </div>
        }
        return (
            <div>
                {spinLoading}
                <Table
                    style={{fontSize:'12px'}}
                    rowHeight={30}
                    headerHeight={30}
                    rowsCount={sortedDataList.length}
                    onColumnResizeEndCallback={this._onColumnResizeEndCallback}
                    isColumnResizing={false}
                    onColumnReorderEndCallback={this._onColumnReorderEndCallback}
                    isColumnReordering={false}
                    width={containerWidth_hide_left}
                    height={containerHeight}
                    {...this.props}>

                    <Column
                        header={<Cell></Cell>}
                        cell={({rowIndex}) => (<Cell>{rowIndex+1}</Cell>)}
                        fixed={true}
                        width={50}
                    />

                    {
                        tableColumnData.map((e, index) => {

                            if(!e.columnHidden){
                                return(
                                    <Column
                                        key={index}
                                        columnKey={e.columnName}
                                        header={
                                            <SortHeaderCell
                                                onSortChange={this._onSortChange}
                                                sortDir={colSortDirs[e.columnName]} >
                                                {e.showName}
                                            </SortHeaderCell>
                                        }
                                        cell={<TextCell data={sortedDataList} />}
                                        flexGrow={1}
                                        width={columnWidths[e.columnName]}
                                        isResizable={true}
                                        isReorderable={true}
                                        allowCellsRecycling={true}
                                    />
                                )
                            }
                        })
                    }

                    {/*header={<Cell>{e.showName}</Cell>}*/}

                    <Column
                        columnKey=""
                        header={<Cell>操作</Cell>}
                        cell={
                            ({rowIndex}) => (
                                <Cell>
                                    {
                                        rowOperation.map( (e, index) => {
                                            return(
                                                <a key={index} onClick={this.rowHandles.bind(this, e.handleName, sortedDataList[rowIndex])} className={e.iconClass}></a>
                                            )
                                        })
                                    }
                                </Cell>
                            )
                        }
                        flexGrow={1}
                        width={rowOperation.length * 35}
                        rightFixed={true}
                    />
                </Table>
            </div>
        );
    }
}

export default Dimensions({
    getHeight: function(element) {
        return window.innerHeight - 280;
    },
    getWidth: function(element) {
        let widthOffset = 288;
        return window.innerWidth - widthOffset;
    },
    containerStyle: {marginLeft: 5, marginRight: 5 } //, transitionProperty: 'width', transitionDuration: '0.5s', transitionTimingFunction:'linear'
})(FlexGrow);
